package com.bj58.mis.apm.wf;


import com.bj58.mis.apm.wf.util.HttpUtils;
import com.bj58.mis.apm.wf.util.PropertiesUtil;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

/**
 * 〈一句话功能简述〉<br> 
 * 〈过滤器〉
 *
 * @author zhangyu84
 * @create 2018/6/29
 * @since 1.0.0
 */
@WebFilter(urlPatterns = {"/*"})
public class HttpFilter implements Filter {
    FilterConfig filterConfig = null;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        this.filterConfig = filterConfig;
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        String key = PropertiesUtil.getProperties("/application.properties", "key");
        String baseUrl = PropertiesUtil.getProperties("/application.properties", "baseUrl");
        String uri = ((HttpServletRequest) servletRequest).getRequestURI();
        //访问spring服务
        if (uri.contains(key)) {
            String str = null;
            servletResponse.setContentType("application/json; charset=utf-8");
            uri=uri.substring((uri.indexOf(key)+key.length()),uri.length());
            Enumeration<String> parameterNames = servletRequest.getParameterNames();
            StringBuilder parameString=new StringBuilder();
            Map<String, String> parameter = new HashMap<String, String>(16);
            if (parameterNames.hasMoreElements()) {
                parameString.append("?");
                while (parameterNames.hasMoreElements()) {
                    String name = parameterNames.nextElement();
                    String value = servletRequest.getParameter(name);
                    parameString.append(name+"="+value+"&");
                    parameter.put(name, value);
                }
            }
            try {
                PrintWriter out = servletResponse.getWriter();
                if (((HttpServletRequest) servletRequest).getMethod().equalsIgnoreCase("GET")) {

                    str = HttpUtils.get(baseUrl+uri+parameString.substring(0,parameString.length()-1), "UTF-8");
                } else {
                    str = HttpUtils.postParameters(baseUrl+uri, parameter);
                }
                out.write(str);
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            filterChain.doFilter(servletRequest, servletResponse);
        }
    }

    @Override
    public void destroy() {

    }
}
